import { useAirCityStore } from '@/stores/aircity'
const AirCityStore = useAirCityStore()

export class Building {
	Layers: string[] //图层数组
	LayersIds: any //图层id数组
	location: any //坐标信息
	height: number //位移高度(有多少层写多少)
	num: number //位移次数
	spend: number // 每次位移速度
	displacement: number //每次位移距离
	LayerDisplacementNum: number //楼层抽拉位移
	LayerSpend: number //楼层每次位移速度
	LayerDisplacement: number //楼层每次位移距离
	direction: 'east' | 'west' | 'south' | 'north' //楼层抽拉方向
	OpencObjectDatas: any //记录打开后状态的自定义对象数据
	customObjectIds: any //记录关闭状态的自定义对象数据
	isCliakVal: any //需要抽出的楼层层数
	isCliakdata: any //保存抽出的楼层数据以便来进行切换
	IsOnReady: boolean = false //准备状态
	isClose: boolean = true //是否处于关闭状态
	isStopRun: boolean = true //是否处于不在运动状态
	_needObjectDatas: any //需要进行操作的自定义对象数据
	_setOpenTimer: any //SetOpen的定时器
	_setCloseTimer: any //SetClose的定时器
	_clickLayerCurrentTimer: any //ClickLayer抽拉当前层的定时器
	_clickLayerLastTimer: any //ClickLayer抽拉上一层的定时器
	_clickLayerSaveTimer: any //ClickLayer抽拉同一层的定时器
	_isClickLayerneedClose: boolean = true //是否需要关闭
	_NeedHidelayers: any //需要隐藏显示的楼层
	hideIds: any
	pianyi: number //偏移

	constructor(options: {
		Layers: string[]
		height?: number
		num?: number
		spend?: number
		displacement?: number
		LayerDisplacementNum?: number
		LayerSpend?: number
		direction?: 'east' | 'west' | 'south' | 'north' //东西南北
		LayerDisplacement?: number
		location?: any
		_NeedHidelayers?: any
		pianyi?: number
		infoTree?: any
	}) {
		this.Layers = options.Layers
		this.location = options.location || [0, 0, 0]
		this.height = options.height || 4
		this.num = options.num || 10
		this.spend = options.spend || 20
		this.displacement = options.displacement || 0.2
		this.LayerDisplacementNum = options.LayerDisplacementNum || 30
		this.LayerSpend = options.LayerSpend || 20
		this.LayerDisplacement = options.LayerDisplacement || 0.5
		this.direction = options.direction || 'north'
		this._NeedHidelayers = options._NeedHidelayers || []
		this.pianyi = options.pianyi || 0
		this.OpencObjectDatas = []
		this.customObjectIds = []
		this.isCliakVal = null
		this.isCliakdata = null
		this.IsOnReady = false
		this.isClose = true
		this.isStopRun = true
	}

	/**
	 * @description: 通过TileLayer添加自定义对象并隐藏原始图层
	 * @param {this.tileLayers} 图层id及objectId
	 * @return {*}
	 */
	async addcustomObject(): Promise<any> {
		if (!this.Layers.length) return

		this.LayersIds = this.Layers.map((layerName: string) =>
			this._GetTreeIdByName(layerName),
		)
		const { data } = await __g.tileLayer.getObjectIDs(this.LayersIds)

		const ctmObjArr = data.map(
			(item: { id: string; objectIds: string[] }, index: number) => {
				const id = `${item.id}@${index}`
				const tileLayerId = item.id
				const objectId = item.objectIds

				this.customObjectIds.push(id)
				return {
					id,
					tileLayerId,
					objectId,
					smoothMotion: 0, //1: 平滑插值，0: 跳跃
					coordinateType: 0,
					//location, //保持原有的模型坐标
					//rotation, //保持原有的模型旋转值
					// scale, //保持原有的模型大小
					UserData: JSON.stringify(this.Layers.length - index), //定义用户自定义数据 用来后面点击模型获取到楼层信息
					groupId: `拆楼`,
				}
			},
		)
		await __g.customObject.delete(this.customObjectIds)
		__g.customObject.addByTileLayer(ctmObjArr, null)
		__g.infoTree.hide(this.LayersIds, null)

		const getctmObjResult: any = await __g.customObject.get(this.customObjectIds)
		this._needObjectDatas = getctmObjResult.data
		this.IsOnReady = true
		console.log('%c 准备完毕', 'color:green')
	}

	/**
	 * @description: 开启模拟楼层拆解
	 * @param {*}
	 * @return {*}
	 */
	async SetOpen(): Promise<any> {
		// 是否拿到模型信息
		if (this.IsOnReady) {
			// 只有引动完毕后才可以继续下一步操作
			if (this.isStopRun) {
				// 已经处于关闭状态
				if (this.isClose) {
					// 打开位移状态
					this.isStopRun = false
					let i = this.displacement
					this._setOpenTimer = setInterval(() => {
						if (i > this.num) {
							/**
							 * @description: 使用递归来使所有模型按照顺序来修改位置信息  记录打开后的位置
							 * @param {number} j
							 * @param {number} length
							 * @return {*}
							 */
							const setLocationDatas = (j: number, length: number) => {
								this._needObjectDatas[j] = {
									...this._needObjectDatas[j],
									location: [
										this._needObjectDatas[j].location[0],
										this._needObjectDatas[j].location[1],
										this._needObjectDatas[j].location[2] +
											(i - this.displacement) * (this.height - j), // i - this.displacement 清除一次位移
									],
								}
								if (++j < length) {
									setLocationDatas(j, length)
								}
							}

							setLocationDatas(0, this._needObjectDatas.length)
							this.isClose = false
							// 关闭位移状态
							this.isStopRun = true
							clearInterval(this._setOpenTimer)
							return
						}
						// __g.customObject.updateBegin();

						/**
						 * @description: 使用递归来改变所有模型位置
						 * @param {number} j
						 * @param {number} length
						 * @return {*}
						 */
						const setLocation = (j: number, length: number) => {
							__g.customObject.setLocation(
								this._needObjectDatas[j].id,
								[
									this._needObjectDatas[j].location[0],
									this._needObjectDatas[j].location[1],
									this._needObjectDatas[j].location[2] + i * (this.height - j),
								],
								null,
							)
							if (++j < length) {
								setLocation(j, length)
							}
						}
						__g.customObject.updateBegin()

						setLocation(0, this._needObjectDatas.length)
						__g.customObject.updateEnd()

						i += this.displacement
					}, this.spend)
				} else {
					console.log('%c 已经是开启状态', 'color:red')
				}
			} else {
				console.log('%c 正处于位移状态，请稍后', 'color:red')
			}
		} else {
			console.log('%c 尚未获取到模型信息，请稍后', 'color:red')
		}
	}

	async SetClose(): Promise<any> {
		if (this.IsOnReady) {
			if (this.isStopRun) {
				if (!this.isClose) {
					// 把之前隐藏的对象显示出来

					this.hideIds && __g.customObject.show(this.hideIds)

					// 打开位移状态
					this.isStopRun = false
					let i = this.displacement
					this._setCloseTimer = setInterval(() => {
						if (i > this.num) {
							const setLocationDatas = (j: number, length: number) => {
								this._needObjectDatas[j] = {
									...this._needObjectDatas[j],
									location: [
										this._needObjectDatas[j].location[0],
										this._needObjectDatas[j].location[1],
										this._needObjectDatas[j].location[2] -
											(i - this.displacement) * (this.height - j),
									],
								}
								if (++j < length) {
									setLocationDatas(j, length)
								}
							}
							setLocationDatas(0, this._needObjectDatas.length)
							// 情况楼层抽出的数据
							this.isCliakVal = null
							this.isClose = true
							// 关闭位移状态
							this.isStopRun = true
							clearInterval(this._setCloseTimer)
							return
						}
						// __g.customObject.updateBegin();
						const setLocation = (j: number, length: number) => {
							__g.customObject.setLocation(
								this._needObjectDatas[j].id,
								[
									this._needObjectDatas[j].location[0],
									this._needObjectDatas[j].location[1],
									this._needObjectDatas[j].location[2] - i * (this.height - j),
								],
								null,
							)
							if (++j < length) {
								setLocation(j, length)
							}
						}
						__g.customObject.updateBegin()
						setLocation(0, this._needObjectDatas.length)
						__g.customObject.updateEnd()
						i += this.displacement
					}, this.spend)
				} else {
					console.log('%c 已经是关闭状态', 'color:red')
				}
			} else {
				console.log('%c 正处于位移状态，请稍后', 'color:red')
			}
		} else {
			console.log('%c 尚未获取到模型信息，请稍后', 'color:red')
		}
	}

	async ClickLayer({ val = 0, status = true }): Promise<any> {
		const newval = this._needObjectDatas.length - val
		// 校准方向
		const pianyiDisplacement =
			this.pianyi / (this.LayerDisplacementNum / this.LayerDisplacement)

		// 需要启动隐藏的楼层数据
		const NeedHideLayer = this._needObjectDatas.length - newval
		// 需要隐藏其他的楼层数据
		const NeedhideIther = this._needObjectDatas
			.map((item: any, index: number) => {
				if (index < newval) {
					return item
				}
			})
			.filter((mon: any) => mon)

		if (this.IsOnReady) {
			if (this.isStopRun) {
				// 把之前隐藏的对象显示出来
				this.hideIds && __g.customObject.show(this.hideIds)
				// 在楼宇关闭状态不能进行
				if (!this.isClose) {
					// console.log(this._NeedHidelayers);
					// console.log(NeedHideLayer);

					// 不需要隐藏楼层
					if (this._NeedHidelayers.indexOf(NeedHideLayer) === -1) {
						// 顶层不启动位移
						// if (newval !== 0) {
						// 状态为打开楼层并且点击的不是同一层
						if (status && this.isCliakVal !== newval) {
							// 定位到该楼层
							// __g.customObject.focus(this._needObjectDatas[newval].id, 80, 2);
							// 打开位移状态
							this.isStopRun = false
							let i = this.LayerDisplacement
							let I_pianyi = pianyiDisplacement
							this._clickLayerCurrentTimer = setInterval(() => {
								if (i + this.LayerDisplacement > this.LayerDisplacementNum) {
									// 运动完毕后保存位置等信息
									this.isCliakdata = {
										...this._needObjectDatas[newval],
										location: [
											this._needObjectDatas[newval].location[0] +
												(this.direction === 'east'
													? i
													: this.direction === 'west'
													? -i
													: this.direction === 'south' && this.pianyi
													? I_pianyi
													: 0),
											this._needObjectDatas[newval].location[1] +
												(this.direction === 'north'
													? i
													: this.direction === 'south'
													? -i
													: 0),
											this._needObjectDatas[newval].location[2],
										],
									}
									// 关闭位移状态
									this.isStopRun = true
									this._isClickLayerneedClose = false
									clearInterval(this._clickLayerCurrentTimer)
									return
								}
								// 开始抽出楼层
								__g.customObject.setLocation(
									this._needObjectDatas[newval].id,
									[
										this._needObjectDatas[newval].location[0] +
											(this.direction === 'east'
												? i
												: this.direction === 'west'
												? -i
												: this.direction === 'south' && this.pianyi
												? I_pianyi
												: 0),
										this._needObjectDatas[newval].location[1] +
											(this.direction === 'north'
												? i
												: this.direction === 'south'
												? -i
												: 0),
										this._needObjectDatas[newval].location[2],
									],
									null,
								)
								i += this.LayerDisplacement
								I_pianyi += pianyiDisplacement
							}, this.LayerSpend)
							if (
								(!this._isClickLayerneedClose && this.isCliakVal) ||
								this.isCliakVal === 0
							) {
								//   // 关闭位移状态
								// this.isStopRun=true
								// console.log(this.isCliakdata, "this.isCliakdata");

								let ii = this.LayerDisplacement
								let II_pianyi = pianyiDisplacement

								this._clickLayerLastTimer = setInterval(async () => {
									if (ii + this.LayerDisplacement > this.LayerDisplacementNum) {
										// 关闭位移状态
										this.isStopRun = true
										clearInterval(this._clickLayerLastTimer)
										return
									}

									__g.customObject.setLocation(
										this.isCliakdata.id,
										[
											this.isCliakdata.location[0] -
												+(this.direction === 'east'
													? ii
													: this.direction === 'west'
													? -ii
													: this.direction === 'south' && this.pianyi
													? II_pianyi
													: 0),
											this.isCliakdata.location[1] -
												(this.direction === 'north'
													? ii
													: this.direction === 'south'
													? -ii
													: 0),
											this.isCliakdata.location[2],
										],
										null,
									)
									ii += this.LayerDisplacement
									II_pianyi += pianyiDisplacement
								}, this.LayerSpend)
							}

							this.isCliakVal = newval
						} else if (this.isCliakVal === newval && !status) {
							this.isStopRun = false
							let ii = this.LayerDisplacement
							let I_pianyi = pianyiDisplacement
							this._clickLayerSaveTimer = setInterval(async () => {
								if (ii + this.LayerDisplacement > this.LayerDisplacementNum) {
									// 关闭位移状态
									this.isStopRun = true
									// 改变该楼层位置信息
									this.isCliakdata = {
										...this._needObjectDatas[newval],
										location: [
											this._needObjectDatas[newval].location[0] -
												(this.direction === 'east'
													? ii
													: this.direction === 'west'
													? -ii
													: this.direction === 'south' && this.pianyi
													? I_pianyi
													: 0),
											this._needObjectDatas[newval].location[1] -
												(this.direction === 'north'
													? ii
													: this.direction === 'south'
													? -ii
													: 0),
											this._needObjectDatas[newval].location[2],
										],
									}
									this._isClickLayerneedClose = true
									this.isCliakVal = null
									clearInterval(this._clickLayerSaveTimer)
									return
								}
								__g.customObject.setLocation(
									this.isCliakdata.id,
									[
										this.isCliakdata.location[0] -
											(this.direction === 'east'
												? ii
												: this.direction === 'west'
												? -ii
												: this.direction === 'south' && this.pianyi
												? I_pianyi
												: 0),
										this.isCliakdata.location[1] -
											(this.direction === 'north'
												? ii
												: this.direction === 'south'
												? -ii
												: 0),
										this.isCliakdata.location[2],
									],
									null,
								)
								ii += this.LayerDisplacement
								I_pianyi += pianyiDisplacement
							}, this.LayerSpend)
						}
						// } else {
						//     console.log("%c 顶层不开启抽拉", "color:red");
						// }
					} else {
						console.log(NeedhideIther, 'NeedhideIther')
						this.hideIds = NeedhideIther.map((item: { id: any }) => item.id)
						// 关闭楼层
						if (this.isCliakVal) {
							this.isStopRun = false
							let ii = 1
							let II_pianyi = 1
							this._clickLayerSaveTimer = setInterval(async () => {
								if (ii > this.LayerDisplacementNum) {
									// 关闭位移状态
									this.isStopRun = true
									// 改变该楼层位置信息
									this.isCliakdata = {
										...this._needObjectDatas[newval],
										location: [
											this._needObjectDatas[newval].location[0] -
												(this.direction === 'east'
													? ii
													: this.direction === 'west'
													? -ii
													: this.direction === 'south'
													? II_pianyi
													: 0),
											this._needObjectDatas[newval].location[1] -
												(this.direction === 'north'
													? ii
													: this.direction === 'south'
													? -ii
													: 0),
											this._needObjectDatas[newval].location[2],
										],
									}
									this._isClickLayerneedClose = true
									this.isCliakVal = null

									clearInterval(this._clickLayerSaveTimer)
									return
								}
								__g.customObject.setLocation(
									this.isCliakdata.id,
									[
										this.isCliakdata.location[0] -
											(this.direction === 'east'
												? ii
												: this.direction === 'west'
												? -ii
												: this.direction === 'south'
												? II_pianyi
												: 0),
										this.isCliakdata.location[1] -
											(this.direction === 'north'
												? ii
												: this.direction === 'south'
												? -ii
												: 0),
										this.isCliakdata.location[2],
									],
									null,
								)
								ii += this.LayerDisplacement
								II_pianyi += pianyiDisplacement
							}, this.LayerSpend)
						}
						if (status) {
							__g.customObject.hide(this.hideIds)
						} else {
							__g.customObject.show(this.hideIds)
						}
					}
				} else {
					console.log('%c 请先开启楼层', 'color:red')
				}
			} else {
				console.log('%c 正处于位移状态，请稍后', 'color:red')
			}
		} else {
			console.log('%c 尚未获取到模型信息，请稍后', 'color:red')
		}
	}

	//根据图层名获取图层id
	_GetTreeIdByName(n: string | string[]) {
		const ids = AirCityStore.GetTreeIdByName(n)
		return ids.length == 1 ? ids[0] : ids
	}

	DelAll() {
		__g.customObject.delete(this.customObjectIds, null)
	}

	focusThis() {
		__g.customObject.focus(
			this.customObjectIds,
			40,
			2,
			[-19.203054, -163.275757, 0],
			null,
		)
	}
}
